const db = require("../../../db");
const { SYSTEM_ERROR, NULL_ERROR } = require("../../../utils/errorCode");
exports.main = (req, res) => {
    // 需要的数据
    // （省份 城市 区域 详细地址） 手机号 收货人名称 是否为默认地址
    const { consigneeName, addressDetail, city, province, county, isDefault, phone, addressId } = req.body;
    if (!consigneeName || !addressDetail || !city || !province || !county || !isDefault || !phone) {
        return res.err(NULL_ERROR);
    }
    console.log(addressId);
    if (addressId) {
        console.log(21312);
    }
    // res.sd(cart);
    const { userId } = req.auth;
    const fullAddress = province + city + county + addressDetail;

    const data = {
        consigneeName, addressDetail, city, province, county, isDefault, userId, phone, fullAddress
    }

    // todo 判断数据是否正确
    if (isDefault === '1') {
        // 如果设置为默认地址，先把其他地址的默认设为0
        const defaultSql = `update address
                            set isDefault = 0
                            where userId = ?`;
        db.query(defaultSql, userId, (err, result) => {
            if (err) {
                console.log(err);
                return res.err(SYSTEM_ERROR);
            }
            if (addressId) {
                updateAddress();
            } else {
                insertAddress();
            }

        })

    } else {
        if (addressId) {
            updateAddress();
        } else {
            insertAddress();
        }

    }

    function insertAddress() {
        // 添加地址
        const sql = `insert into address
                     set ?`;
        db.query(sql, data, (err, result) => {
            if (err) {
                console.log(err);
                return res.err(SYSTEM_ERROR);
            }

            return res.sid(result.insertId);
        })
    }
    function updateAddress() {
        // 修改地址
        const sql = `update address
         set ? where addressId = ?`;
        db.query(sql, [data, addressId], (err, result) => {
            if (err) {
                console.log(err);
                return res.err(SYSTEM_ERROR);
            }

            return res.sm("修改地址成功");
        })
    }
}

